//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ruoyi.common.utils;

import java.util.stream.Stream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

public class WebUtils extends org.springframework.web.util.WebUtils {
    public static final String REQUEST_ID_ATTRIBUTE = "javax.servlet.request_id";
    public static final String X_REAL_IP_HEADER = "X-Real-IP";
    public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For";

    public WebUtils() {
    }

    public static StringBuilder getServerUri(ServletRequest request) {
        String scheme = request.getScheme();
        StringBuilder uri = new StringBuilder();
        uri.append(scheme).append("://").append(request.getServerName());
        int serverPort = request.getServerPort();
        if (serverPort < 0) {
            serverPort = 80;
        }

        if ("https".equals(scheme) && 443 != serverPort || "http".equals(scheme) && 80 != serverPort) {
            uri.append(":").append(serverPort);
        }

        return uri;
    }

    public static StringBuilder getApplicationUri(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return getServerUri(request).append("/".equals(contextPath) ? "" : contextPath);
    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String realIp = request.getHeader("X-Real-IP");
        if (realIp != null) {
            return realIp;
        } else {
            String remoteAddr = request.getHeader("X-Forwarded-For");
            if (StringUtils.isEmpty(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }

            return remoteAddr != null && remoteAddr.length() > 15 ? (String)Stream.of(remoteAddr.split(",")).filter((s) -> {
                return !"unknown".equalsIgnoreCase(s);
            }).findFirst().orElse(null) : remoteAddr;
        }
    }
}
